import axios from 'axios'
import apiUrls from 'common/api-urls'

function sortByDesc(a, b) {
  return b.sortNo - a.sortNo;
}

function sortByAsc(a, b) {
  return a.sortNo - b.sortNo;
}

function getRootList(rawMenuList) {
  const rootList = []
  rawMenuList.forEach(item => {
    if (item.parentId === '0') {
      rootList.push(item)
    }
  })
  return rootList
}

function queryPermissionFromAllList(menuId, allMenuList) {
  const matchedItmes = allMenuList.filter(item => item.id === menuId)
  const permission = matchedItmes.length > 0 ? matchedItmes[0]['permission'] : ''
  return permission
}

function getChildrenList(pid, rawMenuList) {
  const childrenList = []
  rawMenuList.forEach(item => {
    if (item.parentId === pid) {
      childrenList.push(item)
    }
  })

  return childrenList
}

function getChildrenListByRootList(menuList, rawMenuList, allMenuList) {
  if (menuList.length > 0) {
    menuList.forEach(item => {
      const childrenList = getChildrenList(item.id, rawMenuList)
      if (allMenuList && allMenuList.length > 0) {
        item.permission = queryPermissionFromAllList(item.id, allMenuList)
      }
      item.children = childrenList
      item.hasChildren = childrenList.length > 0
      if (childrenList.length > 0) {
        getChildrenListByRootList(childrenList, rawMenuList, allMenuList)
      }
    })
  }
}

export function getNormalMenuList(rawMenuList, allMenuList) {
  const ortByDesc = false
  let menuList = []

  rawMenuList.sort(ortByDesc ? sortByDesc : sortByAsc)
  menuList = getRootList(rawMenuList)
  getChildrenListByRootList(menuList, rawMenuList, allMenuList)

  return menuList
}

export function getLeftMenuList(params) {
  return axios.get(apiUrls.getMenuList, {
    params: {
      ...params
    }
  })
}

export function getAllMenuList(params) {
  // const defaultParams = {
  //   pageSize: 99999
  // }
  // params = Object.assign(defaultParams, params)
  return axios.get(apiUrls.getAllMenuList, {
    params: {
      ...params
    }
  })
}

export function decorateMenuList(rawMenuList, allMenuList) {
  const menuNormalList = getNormalMenuList(rawMenuList, allMenuList)
  // console.info(menuNormalList)
  return menuNormalList
}

export function getMenuItemByMenuUrl(menuUrl, allMenuList) {
  const stack = [...allMenuList]
  while (stack.length) {
    const currentMenuItem = stack[0]
    if (currentMenuItem.menuUrl === menuUrl) {
      return currentMenuItem
    }
    if (currentMenuItem.hasChildren && currentMenuItem.children && currentMenuItem.children.length) {
      stack.push(...currentMenuItem.children)
    }
    stack.shift()
  }
  return {}
}
